package com.ls.lserp.modules.trade.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.modules.sys.entity.SendEmailMessage;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.dbaccess.Entity.PackageCustomEntity;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.trade.entity.BookingOrders;
import com.ls.lserp.modules.trade.entity.ConsignmentNote;
import com.ls.lserp.modules.trade.entity.CustomEnchase;
import com.ls.lserp.modules.trade.service.ConsignmentNoteService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;
import com.ls.lserp.modules.sys.utils.UserUtils;
/**
 * @ClassName: HandBookController
 * @Description: 订舱委托单
 * 
 * @author 
 * @date 2017年3月22日 下午17:20:00
 *
 */



@Controller
@RequestMapping(value = "${adminPath}/consignment/note")
public class ConsignmentNoteController extends BaseController{
	
		@Autowired
		// 保存 编辑 删除 方法
		private ConsignmentNoteService consignmentNoteService;
		@Autowired
		Configuration freemarkerConfiguration;
		@ModelAttribute
		public ConsignmentNote get(@RequestParam(required=false) String id) {
			
			// 判断id是否为空
			if (StringUtils.isNotBlank(id)){
				
				// 执行查询语句 查询基本信息
				return consignmentNoteService.get(Long.parseLong(id));
			}else{
				
				// 若为空，实例化
				return new ConsignmentNote();
			}
		}
		
		
		/**
		 * @Title: 画面跳转用
		 * @return url
		 */
		@RequiresPermissions("consignment:note:view")
		@RequestMapping(value = { "" })
		public String list(Model model) {
			// 画面跳转
			return "modules/trade/consignmentNote";
		}
		
		
		/**
		 * @Title: 画面检索
		 * @Description: 查询页面
		 * @param bookingOrders
		 * @param request
		 * @param response
		 * @param model
		 * @return searchList
		 * @throws Exception
		 */
		@RequiresPermissions("consignment:note:view")
		@RequestMapping(value = { "searchList" })
		@ResponseBody
		public String searchList(ConsignmentNote consignmentNote, HttpServletRequest request, HttpServletResponse response,
				Model model) throws Exception {
			Map<Object, Object> listMap = new HashMap<Object, Object>();
			// ajax回调时使用的一览list名
			request.setAttribute(Global.LIST_NAME, "bookingOrders");
			// 拼接字符串供分页使用
			StringBuilder searchParam = new StringBuilder();
			/*// 合同订单号
			searchParam.append("&indentId=");
			searchParam.append(consignmentNote.getIndentId());*/
			// 客户
			searchParam.append("&ognizationNameB=");
			searchParam.append(consignmentNote.getOgnizationNameB());		
			//开始日期
			searchParam.append("&dateStart=");
			searchParam.append(consignmentNote.getDateStart());
			//结束日期
			searchParam.append("&dateEnd=");
			searchParam.append(consignmentNote.getDateEnd());
			// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam);
			
			// 查询一览页面数据
			Page<ConsignmentNote> page = consignmentNoteService.findList(new Page<ConsignmentNote>(request, response),
					consignmentNote);
			// 读取系统路径
			String strUri = request.getContextPath() + Global.getAdminPath();
			// 读取文件生成字符串
			String strHtml = "";
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("bookingOrderss", page.getList());
			map.put("pageNo", page.getPageNo());
			map.put("pageSize", page.getPageSize());
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("consignmentNote.ftl"), map);
			listMap.put("bookingOrders", strHtml);
			listMap.put("page", page.getHtml());

			// ajax返回结果
			return renderString(response, listMap);
		}
		
		
		
		/**
		 * 
		 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
		 * 3：读取到输入流后，需要读取生成字节流
		 * 
		 * @param filePath
		 * @return html
		 */
		public String readTxtFile(String filePath) {
			String strHtml = "";
			try {
				String encoding = "UTF-8";
				File file = new File(filePath);
				// 判断文件是否存在
				if (file.isFile()) {
					InputStreamReader read = new InputStreamReader(
							// 考虑到编码格式
							new FileInputStream(file), encoding);
					BufferedReader bufferedReader = new BufferedReader(read);
					String lingText = null;
					while ((lingText = bufferedReader.readLine()) != null) {
						strHtml += lingText;
					}
					read.close();
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return strHtml;
		}
		

		/**
		 * 创建订舱委托单信息窗口
		 * 
		 * @return
		 */

		@RequiresPermissions("consignment:note:view")
		@RequestMapping(value = {"createbookorder"})
		public String createbookorder(ConsignmentNote consignmentNote, HttpServletRequest request, HttpServletResponse response,
				Model model){
			if (consignmentNote.getId()!=null) {
				List<ConsignmentNote> consignmentNoteList = consignmentNoteService.findBookingByID(consignmentNote);
				consignmentNote = consignmentNoteService.getBooking(consignmentNote);
				consignmentNote.setConsignmentNoteList(consignmentNoteList);
			}
	   	    //将查询结果赋值mvc model层返回jsp页面
			model.addAttribute("consignmentNote",consignmentNote);
			//返回页面地址
			return "modules/trade/consignmentNoteCreate";
		}
		
		/**
	     * 进入订舱箱单页面
	     * @param enchase
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("consignment:note:view")
	    @RequestMapping(value = "findPackageDetail")
	    public String findPackageDetail(ConsignmentNote consignmentNote, HttpServletRequest request, HttpServletResponse response,
	    		Model model) {
	    	List<CustomEnchase> consignmentNotes = consignmentNoteService.findPackageDetail(consignmentNote);
	        // 返回页面地址
	        return renderString(response, consignmentNotes);
	    }
		
		/**
	     * 进入订舱箱单页面
	     * @param enchase
	     * @param model
	     * @return
	     */ 
	    @RequiresPermissions("consignment:note:view")
	    @RequestMapping(value = "BookingSheet")
	    public String BookingSheet(PackageCustomEntity packageCustomEntity, HttpServletRequest request, HttpServletResponse response,
	    		Model model) {
	        // 将查询结果赋值mvc model层返回jsp页面
	        model.addAttribute("packageCustomEntity", packageCustomEntity);
	        
	        // 返回页面地址
	        return "modules/trade/consignmentNotePacking";
	    }
	    
	    /**
		 * @Title: 画面检索
		 * @Description: 查询页面
		 * @param enchase
		 * @param request
		 * @param response
		 * @param model
		 * @return searchPackingList
		 * @throws ResourceException
		 */
		@RequiresPermissions("consignment:note:view")
		@RequestMapping(value = { "searchPackingList" })
		@ResponseBody
		public String searchPackingList(PackageCustomEntity packageCustomEntity, HttpServletRequest request, HttpServletResponse response,
				Model model) throws ResourceException {
			Map<Object, Object> listMap = new HashMap<Object, Object>();

			// ajax回调时使用的一览list名
			request.setAttribute(Global.LIST_NAME, "packageCustom");

			// 拼接字符串供分页使用
			StringBuilder searchParam = new StringBuilder();
			searchParam.append("&packageNo=");
			searchParam.append(packageCustomEntity.getPackageNo());
			searchParam.append("&deliveryDate=");
			searchParam.append(packageCustomEntity.getDeliveryDate());
			
			// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
			
			// 查询一览页面数据
			packageCustomEntity.setPackageStatus(ResourcesUtil.getConfig("package_status_packed"));
			Page<PackageCustomEntity> page = consignmentNoteService.findpackingList(new Page<PackageCustomEntity>(request, response),packageCustomEntity);
			String strHtml = "";
			try{
				Map<String, Object>  map = new HashedMap();
				map.put("PackingList",page.getList());
				map.put("pageNo",page.getPageNo());
				map.put("pageSize",page.getPageSize());
				strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("consignmentNotePacking.ftl"), map);
			}
			catch (Exception e) {
	            // 记录日志
	            logger.error(e.getMessage(), e);
			}
			
			listMap.put("packageCustom", strHtml);
			listMap.put("page", page.getHtml());

			// ajax返回结果
			return renderString(response, listMap);
		}
		
		
		
	   
	   /**
	    * 保存信息
	    * @param bookingOrders
	    * @param request
	    * @param model
	    * @param response
	    * @return
	    * @throws ResourceException 
	    */
	   @RequiresPermissions("consignment:note:edit")
	   @RequestMapping(value = "save")
	   @ResponseBody
	   public String save(ConsignmentNote consignmentNote, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
	   	
	   	// 判断id是否为null （判断新建或修改）
	   	if(consignmentNote.getId()!=null){
	   		// 编辑数据
	   		// 判断数据是否删除
	   		ConsignmentNote consignmentNoteNew = get(consignmentNote.getId().toString());
	   		// 判断数据是否删除
	           if(consignmentNoteNew==null || BaseEntity.DEL_FLAG_DELETE.equals(consignmentNoteNew.getDeleteFlag())){
	           	// 返回提示信息
	           	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	           }
	   		
	           // 排他处理
	   	    if(consignmentNote.getVersion()==get(consignmentNote.getId().toString()).getVersion()){
	   	    	
	   	    	// 版本号加1
	   	    	consignmentNote.setVersion(consignmentNote.getVersion()+1);
	   	    }else{
	   	    	
	   	    	// 返回提示信息
	   	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
	   	    }
	   	}

	   	// 保存基准数据及子项数据
	   	consignmentNoteService.saveBookingOrders(consignmentNote);
		   try{
		   String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				   + request.getContextPath() + Global.getAdminPath() + "/consignment/note/";
		   //创建成功后发送邮件
		   SendEmailMessage sendEmailMessage = new SendEmailMessage();
		   //邮件主题
		   sendEmailMessage.setDataTheme(ResourcesUtil.getConfig("erp_send_mail_theme06"));
		   //mail正文
		   sendEmailMessage.setDataMessage(ResourcesUtil.getConfig("erp_send_mail_textMessage06"));
		   // 业务员
		   sendEmailMessage.setDataXXX01(UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
		   // 单号
		   sendEmailMessage.setDataXXX02(consignmentNote.getFormId());
		   // 装货港
		   sendEmailMessage.setDataXXX08(consignmentNote.getPortoFloading());
		   // 目的港
		   sendEmailMessage.setDataXXX09(consignmentNote.getPortoFdestiNation());
		   // 件数
		   sendEmailMessage.setDataXXX03(consignmentNote.getTotalNumberofcases().toString());
		   //数量
		   sendEmailMessage.setDataXXX04(consignmentNote.getTotalNumber().toString());
		   // 毛重
		   sendEmailMessage.setDataXXX05(consignmentNote.getTotalWeight().toString());
		   // 净重FORM_NET_WEIGHT
		   sendEmailMessage.setDataXXX06(consignmentNote.getTotalWeight().toString());
		   // 体积
			sendEmailMessage.setDataXXX07(consignmentNote.getTotalVolume().toString());
			//创建日期
			sendEmailMessage.setDataYYMMDD01(DateUtils.formatDate(consignmentNote.getCreateDate(), "yyyy-MM-dd").toString());
		   //发送邮件
			sendEmailMessage.setDataXURLX(url);
		   UserUtils.sendEmail(sendEmailMessage);
		   } catch (Exception e) {
			   logger.error(e.getMessage(), e);
		   }
	   	//
	   	
	   	// 保存成功返回提示信息
	       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName("consignmentNote_create_save_success")));
	   }
	   
	   
	  

	   	/**
		 * 查看页面 
		 * @return
		 */
	   	@RequiresPermissions("consignment:note:view")
		@RequestMapping(value = {"show"})
		public String show(ConsignmentNote consignmentNote, HttpServletRequest request, HttpServletResponse response,Model model){
	   		
	   		List<ConsignmentNote> consignmentNoteList = consignmentNoteService.findBookingByID(consignmentNote);
	   		consignmentNote = consignmentNoteService.getBooking(consignmentNote);
	   		consignmentNote.setConsignmentNoteList(consignmentNoteList);
	   	    //将查询结果赋值mvc model层返回jsp页面
			model.addAttribute("consignmentNote",consignmentNote);
		    //返回页面地址
			return "modules/trade/consignmentNoteShow";
		}
		
	   	/**
		 * 提交信息
		 * @param response
		 * @return
		 */
		@RequiresPermissions("consignment:note:edit")
		@RequestMapping(value = "commit")
		public String commit(ConsignmentNote consignmentNote, HttpServletResponse response) {
			    try {
			    	consignmentNoteService.commitBookingOrders(consignmentNote);
		        } catch (Exception e) {
		            // 记录日志
		            logger.error(e.getMessage(), e);
		        	// 提示错误信息
		            return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		        }
			    
			    // 提示删除成功信息
				return renderString(response,AjaxDone.ok(getText("consignmentNote_create_commit_success")));
		}
	   	
		/**
		 * 删除信息
		 * @param response
		 * @return
		 */
		@RequiresPermissions("consignment:note:edit")
		@RequestMapping(value = "delete")
		public String delete(ConsignmentNote consignmentNote, HttpServletResponse response) {
			    try {
			    	// 执行逻辑删除方法
			    	consignmentNoteService.deleteBookingOrders(consignmentNote);
		        } catch (Exception e) {
		            // 记录日志
		            logger.error(e.getMessage(), e);
		        	// 提示错误信息
		            return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
		        }
			    
			    // 提示删除成功信息
				return renderString(response,AjaxDone.ok(getText("consignmentNote_create_delete_success")));
		}
	   
		/**
		 * 审核页面
		 * @param bookingOrders
		 * @param model
		 * @return
		 */
		@RequiresPermissions("consignment:note:audit")
		@RequestMapping(value = "audit")
		public String audit(BookingOrders bookingOrders,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
			
			// 履历一览取得
			AuditInfo auditInfo = new AuditInfo();
			// 样品生产id
			auditInfo.setAuditRelateId(bookingOrders.getId());
			// 阶段（样品)
			auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_bookingOrders"));
			AuditInfo resultInfo = consignmentNoteService.findAuditInfo(auditInfo);			
			// 样品生产id
			resultInfo.setAuditRelateId(bookingOrders.getId());
			// 样品需求单号
			resultInfo.setAuditRelateNo(bookingOrders.getHsCode());
			// 阶段
			resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_bookingOrders"));
			
			
			// 将实体类值赋给mvc model层返回jsp页面
			model.addAttribute("auditInfo", resultInfo);
			
			// 返回页面地址
			return "modules/order/auditInfo";
		}

		/**
		 * 保存履历信息
		 * @param auditInfo
		 * @param request
		 * @param model
		 * @param response
		 * @return
		 * @throws ResourceException 
		 */
		@RequiresPermissions("specimen:production:edit")
		@RequestMapping(value = "saveAudit")
		@ResponseBody
		public String saveAudit(AuditInfo auditInfo,HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
			
			// 判断数据是否删除
			ConsignmentNote newConsignmentNote=get(Long.toString(auditInfo.getAuditRelateId()));
			
			// 判断数据是否删除
			if(newConsignmentNote==null || BaseEntity.DEL_FLAG_DELETE.equals(newConsignmentNote.getDeleteFlag())){
				// 返回提示信息
				return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
			
		    // 审核结果已经通过,返回错误提示信息
			AuditInfo pAuditResult = new AuditInfo();
			pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
			pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
			if(consignmentNoteService.getAuditResult(pAuditResult)>0){
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
			
			// 排他
			if(auditInfo.getVersion()==get(Long.toString(auditInfo.getAuditRelateId())).getVersion()){
				// 版本号加1
				auditInfo.setVersion(auditInfo.getVersion()+1);
		    	
		    }else{	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
			
		    
		    // 保存样品数据
			consignmentNoteService.saveAuditInfo(auditInfo);
			// 保存成功返回提示信息
		    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "audit_ok_msg")));
		}




}
